<template>
    <el-dialog :visible.sync="isShow" :title="headerTitle" @close="handleClose" center top="2vh" width="864px" append-to-body :fullscreen="fullscreen" @open="onOpen">
        <el-form :model="dialogForm" size="small" label-position="top" label-suffix=":" ref="detailForm" :rules="rules" label-width="90px">
            <el-row :gutter="24" class="mb8" style="max-height:600px;overflow-y:auto">
                <el-col :span="8">
                    <el-form-item :label="$t('basicData.materialName')" prop="materialName">
                        <material-dialog v-model="dialogForm.materialName" @callback="(row) => materialDataCallback(row)" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item :label="$t('basicData.materialNo')" prop="materialCode">
                        <el-input v-model="dialogForm.materialCode" readonly :placeholder="$t('public.inputPl')" clearable />
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item ref="factoryName" :label="$t('mtool.factoryName')" prop="factoryName">
                        <el-autocomplete style="width:100%" popper-class="my-autocomplete" v-model="dialogForm.factoryName" :fetch-suggestions="factoryRemoteMethod" placeholder="请输入内容" @blur="handleFactoryBlur" @select="handleFactorySelect">
                            <i class="el-icon-search el-input__icon" slot="suffix">
                            </i>
                            <template slot-scope="{ item }">
                                {{ item.plantName }}
                            </template>
                        </el-autocomplete>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-card class="box-card">
                        <div slot="header" class="clearfix">
                            <span>{{$t('basicData.text1')}}
                                <el-tooltip class="item" effect="dark" content="例如:“范围”“不合格批次数”五批里面出现2个批次不合格按照加严进行处理" placement="right">
                                    <i class="el-icon-question" style="font-size:16px;cursor:pointer"></i>
                                </el-tooltip>
                            </span>
                        </div>
                        <div class="text item">
                            <el-row :gutter="24" class="mb8">
                                <el-col :span="8">
                                    <el-form-item :label="$t('basicData.content1')" prop="zzyCount" :rules="zzyCountRule()" :required="true">
                                        <el-input v-model="dialogForm.zzyCount" :placeholder="$t('public.inputPl')" clearable />
                                    </el-form-item>
                                </el-col>

                                <el-col :span="8">
                                    <el-form-item :label="$t('basicData.range')" prop="zzyScpoe" :rules="roundRule()" :required="true">
                                        <el-input v-model="dialogForm.zzyScpoe" :placeholder="$t('public.inputPl')" clearable />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item :label="$t('bommaterial.inspectProject')" prop="zzyProjectCode">
                                        <el-select v-model="dialogForm.zzyProjectCode" @change="projectChange" :placeholder="
              $t('public.select_holder', {
                select_holder: $t('bommaterial.projectName'),
              })
            " style="width: 100%" clearable size="small" multiple filterable>
                                            <el-option size="mini" v-for="item in projectList" :key="item.projectName" :label="item.projectName" :value="item.projectCode">
                                            </el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </div>
                    </el-card>
                    <el-card class="box-card card2" style="margin-top:12px">
                        <div slot="header" class="clearfix">
                            <span>
                                {{$t('basicData.text2')}}
                                <el-tooltip class="item" effect="dark" content="例如: 加严处理的物料连续5个批次合格按照正常进行检验" placement="right">
                                    <i class="el-icon-question" style="font-size:16px;cursor:pointer"></i>
                                </el-tooltip>
                            </span>
                        </div>
                        <div class="text item">
                            <el-row :gutter="24" class="mb8">
                                <el-col :span="24">
                                    <el-form-item :label="$t('basicData.content2')" prop="yzzCount" :rules="yzzCountRule()" :required="true">
                                        <el-input v-model="dialogForm.yzzCount" :placeholder="$t('public.inputPl')" clearable />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </div>
                    </el-card>
                    <el-card class="box-card card2" style="margin-top:12px">
                        <div slot="header" class="clearfix">
                            <span>
                                {{$t('basicData.text3')}}
                                <el-tooltip class="item" effect="dark" content="例如:连续5个批次全部合格，按照放宽策略进行检验" placement="right">
                                    <i class="el-icon-question" style="font-size:16px;cursor:pointer"></i>
                                </el-tooltip>
                            </span>
                        </div>
                        <div class="text item">
                            <el-row :gutter="24" class="mb8">
                                <el-col :span="24">
                                    <el-form-item :label="$t('basicData.content2')" prop="zzkCount" :rules="zzkCountRule()" :required="true">
                                        <el-input v-model="dialogForm.zzkCount" :placeholder="$t('public.inputPl')" clearable />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </div>
                    </el-card>
                    <el-card class="box-card card2" style="margin-top:12px">
                        <div slot="header" class="clearfix">
                            <span>
                                {{$t('basicData.text4')}}
                                <el-tooltip class="item" effect="dark" content="例如: 连续5个批次出现2批不合格按照正常策略进行检验" placement="right">
                                    <i class="el-icon-question" style="font-size:16px;cursor:pointer"></i>
                                </el-tooltip>
                            </span>
                        </div>
                        <div class="text item">
                            <el-row :gutter="24" class="mb8">
                                <el-col :span="24">
                                    <el-form-item :label="$t('basicData.content4')" prop="kzzCount" :rules="kzzCountRule()" :required="true">
                                        <el-input v-model="dialogForm.kzzCount" :placeholder="$t('public.inputPl')" clearable />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </div>
                    </el-card>
                </el-col>

            </el-row>

            <!--              编号：-->

            <!--              名称：-->

            <!--              厂区：-->

            <!--              描述信息：-->
            <!-- <el-form-item ref="deviceName" label="描述信息" prop="description">
                <el-input v-model="dialogForm.description" type="textarea" maxlength="1000" :placeholder="$t('public.inputPl')" clearable />
            </el-form-item> -->
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm" :loading="loading" icon="el-icon-document" size="small">{{$t('public.save')}}</el-button>
        </div>
    </el-dialog>
</template>

<script>
import { listAllStemLocationMessage } from '@/api/basic/gaugeMessage'
import { addStemLocation, updateStemLocation } from '@/api/basic/stemLocation'
import { listALLFactory } from '@/api/basic/factory'
import EnjoySelectUser from '@/components/EnjoySelectUser'
import EnjoySelectDeptTree from '@/components/EnjoySelectDeptTree'
import FileUploadInput from '@/components/FileUploadInput'
import MaterialDialog from '@/views/components/MaterialDialog'
import { listProject } from '@/api/basic/project'
import { addRules, editRules } from '@/api/basic/transferRule'

export default {
    name: 'flaw-detial',
    components: {
        EnjoySelectUser,
        EnjoySelectDeptTree,
        FileUploadInput,
        MaterialDialog,
    },

    props: {
        stemForm: {
            type: Object,
        },
        visible: {
            type: Boolean,
            default: false,
        },
        type: [String, Number], //1:新增  2：编辑 3：查看
    },
    computed: {
        isShow: {
            get() {
                return this.visible
            },
            set() {},
        },
        headerTitle() {
            const { type } = this
            let title = ''
            if (type == 1) {
                title =
                    this.$t('public.add') +
                    ' ' +
                    this.$t('basicData.transitionRule')
            }
            if (type == 2) {
                title =
                    this.$t('public.edit') +
                    ' ' +
                    this.$t('basicData.transitionRule')
            }

            return title
        },
    },
    data() {
        return {
            projectList: [],
            loading: false,
            fullscreen: false,
            deviceOptions: undefined,
            factoryOptions: undefined,
            dialogForm: {
                materialCode: undefined,
                materialName: undefined,
                factoryName: undefined,
            },
            // 表单校验
            rules: {
                stemLocationCode: [
                    {
                        required: true,
                        message: '编号不能为空',
                        trigger: 'blur',
                    },
                ],
                materialName: [
                    {
                        required: true,
                        message: this.$t('formValidation.materialNameCannotBeEmpty'),
                        trigger: 'blur',
                    },
                ],
                factoryName: [
                    {
                        required: true,
                        message: this.$t('formValidation.factoryAreaCannotBeEmpty'),
                        trigger: 'blur',
                    },
                ],
                zzyCount: [
                    {
                        required: true,
                        message: '不合格批次数不能为空',
                        trigger: 'blur',
                    },
                ],
                zzyScpoe: [
                    {
                        required: true,
                        message: '范围不能为空',
                        trigger: 'blur',
                    },
                ],
                zzyProjectCode: [
                    {
                        required: true,
                        type: 'array',
                        message: '检验项不能为空',
                        trigger: 'blur',
                    },
                ],
                yzzCount: [
                    {
                        required: true,
                        message: '不合格连续纠正批次数不能为空',
                        trigger: 'change',
                    },
                ],
                zzkCount: [
                    {
                        required: true,
                        message: '连续合格批次数不能为空',
                        trigger: 'change',
                    },
                ],
                kzzCount: [
                    {
                        required: true,
                        message: '合格纠正批次数不能为空',
                        trigger: 'change',
                    },
                ],
            },
            restaurants: [],
            timeout: null,
        }
    },
    watch: {
        visible(val) {
            if (val) {
                this.getFactorySelect()
            }
        },
    },
    created() {
        this.getProjectList()
    },
    methods: {
        remarkRenderHeader(h, { column, $index }) {
            return h('span', [
                h(
                    'span',
                    {
                        style: {
                            color: '#ff1818',
                        },
                    },
                    '*'
                ),
                h('span', column.label),
            ])
        },
        roundRule() {
            return [
                {
                    require: true,
                    validator: (rule, value, callback) => {
                        if (
                            value === null ||
                            value === undefined ||
                            value === ''
                        ) {
                            return callback(new Error('范围不能为空'))
                        }
                        if (isNaN(value)) {
                            return callback(new Error('范围请输入数字'))
                        }
                        callback()
                    },
                    trigger: ['change', 'blur'],
                },
            ]
        },
        zzyCountRule() {
            return [
                {
                    require: true,
                    validator: (rule, value, callback) => {
                        if (
                            value === null ||
                            value === undefined ||
                            value === ''
                        ) {
                            return callback(new Error('不合格批次数不能为空'))
                        }
                        if (isNaN(value)) {
                            return callback(new Error('不合格批次数请输入数字'))
                        }
                        callback()
                    },
                    trigger: ['change', 'blur'],
                },
            ]
        },
        yzzCountRule() {
            return [
                {
                    require: true,
                    validator: (rule, value, callback) => {
                        if (
                            value === null ||
                            value === undefined ||
                            value === ''
                        ) {
                            return callback(
                                new Error('不合格连续纠正批次数不能为空')
                            )
                        }
                        if (isNaN(value)) {
                            return callback(
                                new Error('不合格连续纠正批次数请输入数字')
                            )
                        }
                        callback()
                    },
                    trigger: ['change', 'blur'],
                },
            ]
        },
        zzkCountRule() {
            return [
                {
                    require: true,
                    validator: (rule, value, callback) => {
                        if (
                            value === null ||
                            value === undefined ||
                            value === ''
                        ) {
                            return callback(new Error('连续合格批次数不能为空'))
                        }
                        if (isNaN(value)) {
                            return callback(
                                new Error('连续合格批次数请输入数字')
                            )
                        }
                        callback()
                    },
                    trigger: ['change', 'blur'],
                },
            ]
        },
        kzzCountRule() {
            return [
                {
                    require: true,
                    validator: (rule, value, callback) => {
                        if (
                            value === null ||
                            value === undefined ||
                            value === ''
                        ) {
                            return callback(new Error('合格纠正批次数不能为空'))
                        }
                        if (isNaN(value)) {
                            return callback(
                                new Error('合格纠正批次数请输入数字')
                            )
                        }
                        callback()
                    },
                    trigger: ['change', 'blur'],
                },
            ]
        },
        projectChange(val) {
            let chooseCode = [...val]
            let chooseName = []
            this.projectList.forEach((io) => {
                chooseCode.forEach((ko) => {
                    if (io.projectCode === ko) {
                        chooseName.push(io.projectName)
                    }
                })
            })
            this.dialogForm.zzyProjectName = chooseName
            console.log(val)
        },
        getProjectList() {
            listProject().then((res) => {
                this.projectList = res.rows
            })
        },
        materialDataCallback(row) {
            this.$nextTick(() => {
                this.dialogForm.materialCode = row.materialCode
                this.dialogForm.materialName = row.materialName
                this.dialogForm.factoryName = row.factoryName
                this.dialogForm.factoryCode = row.factoryCode
                this.$refs.detailForm.validateField('materialName')
                this.$refs.detailForm.validateField('factoryName')
            })
        },
        // 窗口打开
        onOpen() {
            if (this.type == '2') {
                this.dialogForm = { ...this.stemForm }
                this.dialogForm.zzyProjectName =
                    this.stemForm.zzyProjectName.split(',')
                this.dialogForm.zzyProjectCode =
                    this.stemForm.zzyProjectCode.split(',')
            }
        },
        /** 发起提交 */
        submitForm: function () {
            this.$refs.detailForm.validate((valid) => {
                let action = this.type == 1 ? addRules : editRules
                if (valid) {
                    this.loading = true
                    let dialogForm = { ...this.dialogForm }
                    dialogForm.zzyProjectCode =
                        dialogForm.zzyProjectCode.join(',')
                    dialogForm.zzyProjectName =
                        dialogForm.zzyProjectName.join(',')
                    action(dialogForm).then(
                        (res) => {
                            this.loading = false
                            if (res.code == 200) {
                                this.$emit('refresh')
                                this.$modal.msgSuccess('操作成功!')
                                this.$emit('update:visible', false)
                            }
                        },
                        (err) => {
                            this.loading = false
                        }
                    )
                }
            })
        },
        handleClose(done) {
            this.$emit('update:visible', false)
            this.$refs['detailForm'].resetFields()
        },

        //工厂模糊查询
        factoryRemoteMethod(val, cb) {
            // listALLFactory({factoryName:val}).then(res=>{
            //   this.factoryOptions = res.data.map(i=>i.deviceName)
            //   cb(res.data)
            // })
            let restaurants = this.restaurants
            let results = val
                ? restaurants.filter(this.createStateFilter(val))
                : restaurants
            clearTimeout(this.timeout)
            this.timeout = setTimeout(() => {
                cb(results)
            }, 1000 * Math.random())
        },
        createStateFilter(queryString) {
            return (state) => {
                return (
                    state.factoryName
                        .toLowerCase()
                        .indexOf(queryString.toLowerCase()) === 0
                )
            }
        },
        getFactorySelect() {
            listALLFactory().then((res) => {
                this.factoryOptions = res.data.map((i) => i.deviceName)
                this.restaurants = res.data
            })
        },
        handleFactorySelect(e) {
            this.dialogForm.factoryName = e.plantName
            this.$refs.factoryName.$emit('el.form.blur')
        },
        handleFactoryBlur(e) {
            const { factoryOptions, dialogForm } = this
            if (!factoryOptions.includes(dialogForm.factoryName)) {
                this.dialogForm.factoryName = ''
            }
        },
        handleExpireTime(e) {
            console.log(e)
            const today = new Date().getTime()
            const val = new Date(e).getTime()
            if (val > today) {
                this.dialogForm.remDay = ~~(
                    (val - today) /
                    1000 /
                    60 /
                    60 /
                    24
                ).toFixed(1)
            } else {
                this.dialogForm.remDay = 0
            }
            this.$forceUpdate()
        },
        handleRespName(e) {
            this.dialogForm.respName = e.name
        },
        handleEmployName(e) {
            this.dialogForm.employName = e.name
        },
        handleRespDept(e) {
            this.dialogForm.respDept = e.name
        },
    },
}
</script>

<style scoped>
::v-deep .el-form--label-top .el-form-item__label {
    padding: 0;
}
::v-deep .el-card {
    padding: 0px !important;
}
::v-deep .card2 .el-form-item__label {
    width: 137px !important;
}
</style>
